import React, { useEffect, useMemo } from "react";
import { createRoot } from "react-dom/client";
import { UserApp, UserAppDetail } from "../serve/interface";
import { Anchor, ConfigProvider, Result, Splitter } from "antd";
import { legacyLogicalPropertiesTransformer, StyleProvider } from "@ant-design/cssinjs";
import zh_CN from "antd/locale/zh_CN";
import { getStore, setStore } from "./utils/store";
import { PreviewTree } from "./components/Preview";
import Markdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight'
import remarkGFM from 'remark-gfm';
import { CustomCode, CustomImage, CustomLinkPreview } from "./components/Editor/EditorMarkdown/components";
import { THEME } from "./utils/theme";
import { createCustomHeading } from "./components/Editor/EditorMarkdown/components/CustomHeading";
import { formatDoc } from "../serve/common";
import "./polyfill"
import { CHROME_VERSION } from "./utils/common";

const postMessage = function (message: any) {
    if (window.parent != window) {
        window.parent.postMessage(message, location.origin)
    }
}

addEventListener('hashchange', () => {
    postMessage({
        type: 'hash.change',
        value: location.hash,
    })
})

interface Meta {
    app: UserApp;
    detail: UserAppDetail;
    docs: Record<number, string>;
}

const App = (meta: Meta) => {
    const { app, detail, docs } = meta
    const params = new URLSearchParams(location.search);
    const [id, setId] = React.useState(params.get("id"));

    useEffect(() => {
        if (id && id != params.get("id")) {
            history.pushState({}, "", `?id=${id}`);
            postMessage({
                type: "doc.change",
                value: id,
            })
        }
    }, [id]);

    const doc = docs[id]
    const [body, anchors] = useMemo(() => {
        const [CustomHeading, items] = createCustomHeading();
        const body = <Markdown skipHtml rehypePlugins={[
            rehypeHighlight,
            remarkGFM,
        ]} className="markdown-body p-4" components={{
            code: CustomCode,
            img: CustomImage,
            a: CustomLinkPreview,
            h1: CustomHeading,
            h2: CustomHeading,
            h3: CustomHeading,
            h4: CustomHeading,
            h5: CustomHeading,
            h6: CustomHeading,
        }} >
            {formatDoc(doc || "").content}
        </Markdown>
        const anchors = <Anchor
            className="overflow-auto"
            items={items}
            getContainer={() => document.querySelector<HTMLDivElement>(".markdown-body").parentElement} />
        setTimeout(() => {
            if (location.hash) {
                document.querySelector<HTMLAnchorElement>(`[href="${location.hash}"]`)?.click();
            }
        }, 100);
        return doc ? [body, anchors] : [];
    }, [doc]);

    return <StyleProvider transformers={[legacyLogicalPropertiesTransformer]} hashPriority={CHROME_VERSION >= 90 ? undefined : "high"}>
        <ConfigProvider locale={zh_CN} theme={THEME}>
            <Splitter className="mx-auto h-[calc(100vh-8px)]"
                onResize={size => {
                    setStore("split_size", size[0])
                    setStore("split_size_right", size[2])
                }}>
                <Splitter.Panel defaultSize={getStore("split_size")} min={200} max={500}>
                    <div className="pt-2 pl-2 flex items-center">
                        <span className="w-10 h-10 p-2.5 text-center float-left shadow rounded">
                            <svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M4.39992 1.83398H3.02492C2.36492 1.83398 1.83325 2.32898 1.83325 2.93398V19.0673C1.83325 19.6723 2.36492 20.1673 3.02492 20.1673H4.39992V1.83398ZM18.9749 1.83398H17.5999V6.94898L15.0333 4.40065L12.4666 6.96732V1.83398H5.86659V20.1673H18.9749C19.6349 20.1673 20.1666 19.6723 20.1666 19.0673V2.93398C20.1666 2.32898 19.6349 1.83398 18.9749 1.83398ZM17.5999 14.6673H8.43325V13.2007H17.5999V14.6673ZM17.5999 11.0007H8.43325V9.53398H17.5999V11.0007Z" fill="#2176FF" />
                            </svg>
                        </span>
                        <b className="pl-2 text-base">{document.title}</b>
                    </div>
                    <PreviewTree app={app} detail={detail} selectKey={Number(id)} onSelectKey={key => setId(key + '')} />
                </Splitter.Panel>
                <Splitter.Panel>
                    {body || (
                        id ? <Result status="404" title="文档不存在或已删除" subTitle="请选择其他文档" /> : null
                    )}
                </Splitter.Panel>
                <Splitter.Panel style={{ overflow: "hidden" }} className="sm:hidden md:block" defaultSize={getStore("split_size_right")} min={200} max={400}>
                    {anchors}
                </Splitter.Panel>
            </Splitter>
        </ConfigProvider>
    </StyleProvider>;
};

const entry = document.createElement("script")
entry.addEventListener('load', function () {
    const meta: Meta = window["__META__"] || { app: {}, detail: { tree: [] }, docs: {} }
    createRoot(document.getElementById("root")).render(<App {...meta} />);
})
entry.src = `meta.js?${Date.now()}`
document.head.appendChild(entry)